package com.zhku.goods.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhku.base.exception.CommonError;
import com.zhku.base.exception.TaoTaoException;
import com.zhku.base.model.PageParams;
import com.zhku.base.model.PageResult;
import com.zhku.goods.feignclient.GoodsIndex;
import com.zhku.goods.feignclient.SearchServiceClient;
import com.zhku.goods.mapper.TtGoodsMapper;
import com.zhku.goods.model.dto.GoodsDto;
import com.zhku.goods.model.po.TtGoods;
import com.zhku.goods.service.TtGoodsService;
import com.zhku.messagesdk.model.po.MqMessage;
import com.zhku.messagesdk.service.MqMessageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class TtGoodsServiceImpl extends ServiceImpl<TtGoodsMapper, TtGoods> implements TtGoodsService {

    @Autowired
    TtGoodsMapper ttGoodsMapper;
    @Autowired
    MqMessageService mqMessageService;
    @Autowired
    SearchServiceClient searchServiceClient;

    @Transactional
    @Override
    public TtGoods createGoods(GoodsDto goodsDto) {
        String url = goodsDto.getUrl();
        if (StringUtils.isEmpty(url)) {
            TaoTaoException.cast("传入商品图片访问地址为空");
        }
        String shopId = goodsDto.getShopId();
        if (StringUtils.isEmpty(shopId)) {
            TaoTaoException.cast("创建商品时传入的店铺id为空");
        }
        String createPeople = goodsDto.getCreatePeople();
        if (StringUtils.isEmpty(createPeople)) {
            TaoTaoException.cast("传入的创建人id为空");
        }
        TtGoods ttGoods = new TtGoods();
        BeanUtils.copyProperties(goodsDto, ttGoods);
        String id = UUID.randomUUID().toString();
        ttGoods.setId(id);
        ttGoods.setChangePeople(createPeople);
        ttGoods.setUpdatetime(LocalDateTime.now());
        ttGoods.setCreatetime(LocalDateTime.now());
        ttGoods.setStatus("0");
        ttGoods.setFlag("0");
        int insert = ttGoodsMapper.insert(ttGoods);
        if (insert <= 0) {
            throw new TaoTaoException("创建商品失败");
        }
        return ttGoods;
    }

    @Transactional
    @Override
    public TtGoods updateGoods(TtGoods ttGoods) {
        String url = ttGoods.getUrl();
        if (StringUtils.isEmpty(url)) {
            TaoTaoException.cast("传入商品图片访问地址为空");
        }
        String shopId = ttGoods.getShopId();
        if (StringUtils.isEmpty(shopId)) {
            TaoTaoException.cast("修改商品时传入的店铺id为空");
        }
        String changePeople = ttGoods.getChangePeople();
        if (StringUtils.isEmpty(changePeople)) {
            TaoTaoException.cast("传入的修改人id为空");
        }
        String id = ttGoods.getId();
        TtGoods ttGoodsOld = ttGoodsMapper.selectById(id);
        if (ttGoodsOld == null) {
            throw new TaoTaoException("当前商品不存在");
        }
        ttGoods.setUpdatetime(LocalDateTime.now());
//        String status = ttGoods.getStatus();
//        GoodsIndex goodsIndex = new GoodsIndex();
//        BeanUtils.copyProperties(ttGoods,goodsIndex);
//        if ("0".equals(status)) {
//            //删除索引库
//            //远程调用
//            Boolean delete = searchServiceClient.delete(goodsIndex);
//            if (!delete) {
//                TaoTaoException.cast("远程调用搜索服务删除商品索引失败");
//            }
//        } else if ("1".equals(status)) {
//            //刚刚创建商品时执行插入操作
//            if ("0".equals(ttGoods.getFlag())) {
//                //向消息表中插入数据
//                saveGoodsPublishMessage(id);
//                ttGoods.setFlag("1");
//            }else{
//                //更新索引库
//                //远程调用
//                Boolean update = searchServiceClient.update(goodsIndex);
//                if (!update) {
//                    TaoTaoException.cast("远程调用搜索服务修改商品索引失败");
//                }
//            }
//        }
        int i = ttGoodsMapper.updateById(ttGoods);
        if (i <= 0) {
            throw new TaoTaoException("修改商品信息失败");
        }
        return ttGoods;
    }

    @Override
    public TtGoods getShop(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new TaoTaoException("传入的商品id为空");
        }
        TtGoods ttGoods = ttGoodsMapper.selectById(id);
        if (ttGoods == null) {
            throw new TaoTaoException("该商品不存在");
        }
        return ttGoods;
    }

    @Override
    public PageResult<TtGoods> getGoodsList(PageParams pageParams, String id) {
        if (StringUtils.isEmpty(id)) {
            throw new TaoTaoException("传入的店铺id为空");
        }
        //拼装查询条件
        LambdaQueryWrapper<TtGoods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TtGoods::getShopId,id);
        //创建page分页参数对象，参数：当前页码数，每页记录数
        Page<TtGoods> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        Page<TtGoods> ttUserAddressPage = ttGoodsMapper.selectPage(page, queryWrapper);
        List<TtGoods> items = ttUserAddressPage.getRecords();
        long counts = ttUserAddressPage.getTotal();
        PageResult<TtGoods> ttUserAddressPageResult = new PageResult<>(items,
                counts,pageParams.getPageNo(),pageParams.getPageSize());
        return ttUserAddressPageResult;
    }

    @Transactional
    @Override
    public TtGoods goodsUp(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new TaoTaoException("传入的商品id未空");
        }
        TtGoods ttGoods = ttGoodsMapper.selectById(id);
        if (ttGoods == null) {
            throw new TaoTaoException("商品不存在");
        }
        ttGoods.setStatus("1");
        ttGoods.setUpdatetime(LocalDateTime.now());
        GoodsIndex goodsIndex = new GoodsIndex();
        BeanUtils.copyProperties(ttGoods,goodsIndex);
        //刚刚创建商品时执行插入操作
        if ("0".equals(ttGoods.getFlag())) {
            //向消息表中插入数据
            saveGoodsPublishMessage(id);
            ttGoods.setFlag("1");
        }else{
            //更新索引库
            //远程调用
            Boolean update = searchServiceClient.update(goodsIndex);
            if (!update) {
                TaoTaoException.cast("远程调用搜索服务修改商品索引失败");
            }
        }
        int i = ttGoodsMapper.updateById(ttGoods);
        if (i <= 0) {
            throw new TaoTaoException("商品上架失败");
        }
        return ttGoods;
    }

    @Transactional
    @Override
    public TtGoods goodsDown(String id) {
        if (StringUtils.isEmpty(id)) {
            throw new TaoTaoException("传入的商品id未空");
        }
        TtGoods ttGoods = ttGoodsMapper.selectById(id);
        if (ttGoods == null) {
            throw new TaoTaoException("商品不存在");
        }
        ttGoods.setStatus("0");
        ttGoods.setUpdatetime(LocalDateTime.now());
        GoodsIndex goodsIndex = new GoodsIndex();
        BeanUtils.copyProperties(ttGoods,goodsIndex);
        //删除索引库
        //远程调用
        Boolean delete = searchServiceClient.delete(goodsIndex);
        if (!delete) {
            TaoTaoException.cast("远程调用搜索服务删除商品索引失败");
        }
        ttGoods.setFlag("0");
        int i = ttGoodsMapper.updateById(ttGoods);
        if (i <= 0) {
            throw new TaoTaoException("商品下架失败");
        }
        return ttGoods;
    }

    /**
     * 保存消息表
     *
     * @param id 商品id
     */
    private void saveGoodsPublishMessage(String id) {
        MqMessage mqMessage = mqMessageService.addMessage("goods_publish", id, null, null);
        if (mqMessage == null) {
            TaoTaoException.cast(CommonError.UNKOWN_ERROR);
        }
    }
}
